package com.learn.dead_letter;

import com.learn.utils.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;

import java.util.HashMap;
import java.util.Map;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/08/23
 * @description ch06 死信
 * 负责创建交换机和队列，配置死信
 */
public class Consumer01 {
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";
    public static final String NORMAL_QUEUE = "normal_queue";
    public static final String DEAD_QUEUE = "dead_queue";
    public static final String NORMAL_ROUTING_KEY = "normal";
    public static final String DEAD_ROUTING_KEY = "dead";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);
        /*
        需要在normal的绑定中设置参数，以实现死信
        可以在控制台上看到
        死信产生的三种方式中的两种在这里设置
        记得更改属性时要先删除队列
         */
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);
        // ttl过期 ms
//        arguments.put("x-message-ttl", 5000);
        // 最大队列长度
//        arguments.put("x-max-length",6);

        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);

        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, NORMAL_ROUTING_KEY);
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, DEAD_ROUTING_KEY);

        // 设置拒绝消息
        channel.basicConsume(NORMAL_QUEUE, false,
                (consumerTag, message) -> {
                    String msg = new String(message.getBody());
                    if(msg.charAt(msg.length() - 1) == '5') {
                        System.out.println("消息被拒绝：" + msg);
                        channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
                    } else {
                        System.out.println("消息：" + msg);
                        channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
                    }
                },
                consumerTag -> {});
    }
}
